//
//  HelpMessageVC.m
//  智慧小区
//
//  Created by 高永杨 on 2017/3/17.
//  Copyright © 2017年 zhongchuang. All rights reserved.
//

#import "HelpMessageVC.h"
#import "HelpViewCell.h"
#import <AFNetworking.h>
#import "HelpDetailVC.h"
#import "SeekHelpDetailVC.h"
#import <MJRefresh.h>
#import "HelpShareModel.h"
#import "ReleaseForHelpVC.h"
@interface HelpMessageVC ()<UITableViewDelegate,UITableViewDataSource,HelpViewCellDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableVie;
/**请求后得到的数据*/
@property(nonatomic,strong)NSMutableArray *dataArr;

//数据加载的原因
/**当前页码*/
@property (nonatomic,assign) NSInteger page;

/**上一次的请求参数*/
@property (nonatomic,strong) NSDictionary *params;
//
/**数据*/
//@property(nonatomic,strong)NSMutableDictionary *dictArr;
@property (weak, nonatomic) IBOutlet UIButton *sureButt;



@end

@implementation HelpMessageVC
static NSString *cellId = @"cellId";
- (void)viewDidLoad {
    [super viewDidLoad];
    
    switch (self.type) {
        case Help:
            [self.sureButt setTitle:@"发布求助信息" forState:UIControlStateNormal];
            break;
        case Love:
              [self.sureButt setTitle:@"发布爱心捐助" forState:UIControlStateNormal];
            break;
        case Resource:
           [self.sureButt setTitle:@"发布资源共享" forState:UIControlStateNormal];
            break;
        default:
            break;
    }
    // Do any additional setup after loading the view from its nib.
    [self.tableVie registerNib:[UINib nibWithNibName:NSStringFromClass([HelpViewCell class]) bundle:nil] forCellReuseIdentifier:cellId];
    [self setuprefresh];
}
-(NSMutableArray *)dataArr
{
    if (!_dataArr) {
        _dataArr = [NSMutableArray arrayWithCapacity:4];
    }
    return _dataArr;
}

-(void)setuprefresh
{
    self.tableVie.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewTopics)];
    //    self.tableVie.mj_header.automaticallyChangeAlpha = YES;
    [self.tableVie.mj_header beginRefreshing];
    self.tableVie.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreTopic)];
}
//区分不同类型的参数
-(void)loadParms:(NSMutableDictionary *)parms
{
    if ([self.myType isEqualToString:@"HelpOther"]) {
        parms[@"token"] = @"e4022b7ca0e3f31048c3c4ac30ae3967";
        switch (self.type) {
            case Help:
                parms[@"category"]=@"1";
                break;
            case Love:
                parms[@"category"]=@"2";
                break;
            default:
                break;
        }
    }else
    {
        parms[@"token"] = @"1";
        switch (self.type) {
            case Help:
                parms[@"category"]=@"1";
                break;
            case Love:
                parms[@"category"]=@"3";
                break;
            case Resource:
                parms[@"category"]=@"2";
                break;
            default:
                break;
        }
    }
}

//#pragma mark - 数据处理
-(void)loadNewTopics
{
    [self.tableVie.mj_footer endRefreshing];
    //发送请求
NSMutableDictionary *parms = [NSMutableDictionary dictionary];
    parms[@"opt"] = @(20);
    parms[@"page"] = @(1);
    [self loadParms:parms];
  
    self.params = parms;
    [[AFHTTPSessionManager manager] GET:GolobaUrl parameters:parms progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary* _Nullable responseObject) {
        [SVProgressHUD showSuccessWithStatus:@"刷新成功"];
        [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
        [self.dataArr removeAllObjects];
        NSArray *arr = responseObject[@"results"];
        for (int i = 0; i<arr.count; i++) {
            HelpShareModel *gongGao = [[HelpShareModel alloc] init];
            [gongGao setValuesForKeysWithDictionary:arr[i]];
            gongGao.helpShareType = self.myType;
            gongGao.helpLoveResource = self.type;
            [self.dataArr addObject:gongGao];
        }
        if (self.params != parms) return ;
        [self.tableVie reloadData];
        [self.tableVie.mj_header endRefreshing];
        self.page = 1;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (self.params != parms) return ;
        [[Toast shareInstance] makeToast:@"刷新失败,请检查网络" duration:2.0];
        [self.tableVie.mj_header endRefreshing];
    }];
}

-(void)loadMoreTopic
{
    [self.tableVie.mj_header endRefreshing];
    self.page++;
    //发送请求
    NSMutableDictionary *parms = [NSMutableDictionary dictionary];
    parms[@"page"] = @(self.page);
    parms[@"opt"] = @(20);
    [self loadParms:parms];
    self.params = parms;
    [[AFHTTPSessionManager manager] GET:GolobaUrl parameters:parms progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary* _Nullable responseObject) {
        if ([responseObject[@"error"] integerValue] != -1) {
            [[Toast shareInstance] makeToast:@"网络加载失败,检查网络" duration:2.0];
            [self.tableVie.mj_footer endRefreshing];
            return ;
        }
        NSArray *arr = responseObject[@"results"];
        if (arr.count<1) {
            [self.tableVie.mj_footer endRefreshingWithNoMoreData];
            return ;
        }
        for (int i = 0; i<arr.count; i++) {
            HelpShareModel *gongGao = [[HelpShareModel alloc] init];
            [gongGao setValuesForKeysWithDictionary:arr[i]];
            gongGao.helpShareType = self.myType;
            gongGao.helpLoveResource = self.type;
            [self.dataArr addObject:gongGao];
        }
        [self.tableVie reloadData];
        [self.tableVie.mj_footer endRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [[Toast shareInstance] makeToast:@"网络加载失败,检查网络" duration:2.0];
        if (self.params != parms) return ;
        [self.tableVie.mj_footer endRefreshing];
        //恢复页码,网络加载失败
        self.page--;
    }];
}





-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  HelpViewCell *cell =  [tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
    cell.delegate = self;
    [cell sendModel:self.dataArr[indexPath.row]];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArr.count;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    SeekHelpDetailVC *detail = [[SeekHelpDetailVC alloc]init];
    detail.temStrID = [self.dataArr[indexPath.row] key_id];
    [self.navigationController pushViewController:detail animated:YES];
}
-(void)sendHelpViewDaiLi:(UIButton *)but
{
    HelpViewCell * cell = (HelpViewCell *)[[but superview] superview];
    NSIndexPath * path = [self.tableVie indexPathForCell:cell];
    //获取按钮所在的cell的row
    HelpDetailVC *helpDetail = [[HelpDetailVC alloc]init];
    helpDetail.tempID = [self.dataArr[path.row] key_id];
    [self.navigationController pushViewController:helpDetail animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)helpLoveBut:(UIButton *)sender {
    switch (self.type) {
        case Help:{
            ReleaseForHelpVC *releaseHelp = [[ReleaseForHelpVC alloc]init];
            [self.navigationController pushViewController:releaseHelp animated:YES];
        }
            break;
        case Love:{
        
        }
            break;
        case Resource:
            
            break;
            
        default:
            break;
    }
}
-(void)closeHeplBut:(UIButton *)senderBut
{
    HelpViewCell * cell = (HelpViewCell *)[[senderBut superview] superview];
    NSIndexPath *path = [self.tableVie indexPathForCell:cell];
    //获取按钮所在的cell的row
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:@"31" forKey:@"opt"];
    HelpShareModel *shareM = self.dataArr[path.row];
    [dict setValue:shareM.key_id forKey:@"helpInfoId"];
    [dict setValue:@"6" forKey:@"state"];
    [[AFHTTPSessionManager manager] POST:GolobaUrl parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
